// electron/controller/TerminalController.ts
import TerminalService from '../service/TerminalService';
import type { IpcMainEvent, WebContents } from 'electron';
import log from 'electron-log/node';

class TerminalController {
  private dataListeners = new Map<number, (data: string) => void>();

  /**
   * 初始化终端及事件绑定，确保每个窗口唯一实例
   */
  setupTerminalEvents(event: IpcMainEvent) {
    const webContents = event.sender;
    const id = webContents.id;

    TerminalService.createPty(id);

    // 防止重复绑定监听（多余解绑动作已在service处理）
    if (this.dataListeners.has(id)) {
      // 已有监听器，跳过或清理
      // 可选：this.removeListener(id);

      log.info(
        `[TerminalController] setupTerminalEvents: Listener already exists for id=${id}`,
      );
    }

    const onData = (data: string) => {
      log.info(`[TerminalController] onData: ${data}`);
      webContents.send('terminal:data', data);
    };

    this.dataListeners.set(id, onData);
    TerminalService.onData(id, onData);

    // 监听窗口销毁，自动清理资源
    const onDestroyed = () => {
      this.dispose(id);
      webContents.removeListener('destroyed', onDestroyed);
    };
    webContents.once('destroyed', onDestroyed);
  }

  /**
   * 关闭终端数据监听，释放资源
   */
  dispose(id: number) {
    TerminalService.dispose(id);
    this.dataListeners.delete(id);
  }

  write(data: string, event: IpcMainEvent) {
    TerminalService.write(event.sender.id, data);
  }

  resize(cols: number, rows: number, event: IpcMainEvent) {
    TerminalService.resize(event.sender.id, cols, rows);
  }

  stop(event: IpcMainEvent) {
    const id = event.sender.id;
    this.dispose(id);
  }

  execPythonFile(filePath: string, event: IpcMainEvent) {
    TerminalService.execPythonFile(event.sender.id, filePath);
  }
}

export default new TerminalController();
